package com.woniuxy.task;

import com.woniuxy.config.RabbitConfig;
import com.woniuxy.service.SysLogOptService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LogTask {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private SysLogOptService sysLogOptService;

    // Redis 中存储日志的列表 key
    private static final String LOG_LIST_KEY = "log:list";

//    @Scheduled(cron = "*/20 * * * * ?")  // 定时执行一次兜底刷新
    public void scheduledFlush() {
        log.error("刷新了生成日志缓存");

        RLock lock = redissonClient.getLock("log:flush:lock");

        Boolean isLocked = false;
        //尝试获取锁，最多等待2秒，锁自动释放时间为10 秒
        try {
            isLocked = lock.tryLock(2,10, TimeUnit.SECONDS);
            if(isLocked){
                List<Object>  logs    = redisTemplate.opsForList()
                        .rightPop(LOG_LIST_KEY,redisTemplate.opsForList().size(LOG_LIST_KEY));
                rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME,RabbitConfig.ROUTING_KEY_DB,logs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //  确保当前线程释放锁（防止死锁）
            if(isLocked && lock.isHeldByCurrentThread()) lock.unlock();
        }
    }
//    @Scheduled(cron = "*/30 * * * * ?")  // 定时执行一次清楚日志
    public void scheduledDeleteLog() {
        log.info("定时任务开始：删除 30 秒前的日志");

        // 当前时间减去 30 秒
        LocalDateTime deadline = LocalDateTime.now().minusSeconds(30);

        int deletedCount = sysLogOptService.removeLogsBefore(deadline);

        log.info("定时任务完成：共删除日志 {} 条", deletedCount);
    }
}
